package com.ibpd.henuocms.tlds;

import java.io.IOException;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.jsp.JspException;

import org.h2.util.StringUtils;
import org.hsqldb.lib.StringUtil;

import com.ibpd.dao.impl.ServiceProxyFactory;
import com.ibpd.henuocms.entity.NodeAttrEntity;
import com.ibpd.henuocms.entity.NodeEntity;
import com.ibpd.henuocms.entity.SubSiteEntity;
import com.ibpd.henuocms.entity.ext.NodeExtEntity;
import com.ibpd.henuocms.service.node.INodeService;
import com.ibpd.henuocms.service.node.NodeServiceImpl;
import com.ibpd.henuocms.service.nodeAttr.INodeAttrService;
import com.ibpd.henuocms.service.nodeAttr.NodeAttrServiceImpl;
import com.ibpd.henuocms.service.subSite.ISubSiteService;
import com.ibpd.henuocms.service.subSite.SubSiteServiceImpl;
import com.ibpd.henuocms.web.controller.web.WebSite;

public class NodeNaviTag extends SimpleBaseTag {
	private String nodeId="";
	private List<NodeExtEntity> nodeList=new ArrayList<NodeExtEntity>();
	@Override
	public void doTag() throws JspException, IOException {
		_init();
		if(nodeList==null){
            return ;
        }
		if(nodeList.size()==0)
			return;
	    getJspContext().getOut().write(getFieldValue());
	    if(getJspBody()!=null)
	    	getJspBody().invoke(null);
	}

	private String getFieldValue(){
		if(nodeList==null){
            return "";
        }
		if(nodeList.size()==0)
			return "";
		StringBuffer sb=new StringBuffer();
//		sb.append("<a href='");
//		String type=getRequest().getParameter("type"); 
//		if(!StringUtils.isNullOrEmpty(type) && type.trim().toLowerCase().equals(WebSite.WEBPAGE_TYPE_VIEWER.toString())){
//			sb.append(getRequest().getContextPath());
//		} 
		NodeEntity nn=new NodeEntity();
		nn.setSubSiteId(nodeList.get(0).getSubSiteId());
		nn.setNodeIdPath("");
		nn.setText("首页");
		sb.append("<a href='/' target='_self'>"+nn.getText()+"</a>&gt;&gt;");
		INodeService nodeServ=(INodeService) ServiceProxyFactory.getServiceProxy(NodeServiceImpl.class);
		for(NodeExtEntity n:nodeList){
			//如果查询正确的话，这里应该只返回一个nodeEntity
			String nodeIdPath=n.getNodeIdPath();
			String[] paths=nodeIdPath.split(",");
			for(String id:paths){
				if(StringUtils.isNumber(id)){
					NodeEntity ne=nodeServ.getEntityById(Long.valueOf(id));
					if(ne!=null)
						sb.append("<a href='"+getNodeUrlDir(ne,getRequest())+"' target='_self'>"+ne.getText()+"</a>&gt;&gt;");
				}
			}
		}
		if(sb.length()>0)
			return sb.toString().substring(0,sb.toString().length()-8);
		return sb.toString();
	}
	private String getNodeUrlDir(NodeEntity node,HttpServletRequest req){
		if(node==null)
			return "";
		ISubSiteService siteServ=(ISubSiteService) ServiceProxyFactory.getServiceProxy(SubSiteServiceImpl.class);
		SubSiteEntity site=siteServ.getEntityById(node.getSubSiteId());
		String idPath=node.getNodeIdPath();
		String[] ids=idPath.split(",");
		Map<Long,String> dirMap=new LinkedHashMap<Long,String>();
		//先把要取的目录都取出来
		INodeAttrService attrService=(INodeAttrService) ServiceProxyFactory.getServiceProxy(NodeAttrServiceImpl.class);
		for(String id:ids){
			if(StringUtil.isEmpty(id))
				continue;
			if(StringUtils.isNumber(id)){
				Long nodeId=Long.parseLong(id);
				NodeAttrEntity attr=attrService.getNodeAttr(nodeId);
				if(attr!=null){
					dirMap.put(nodeId, attr.getDirectory());//理论上这里取出来的目录顺序是正确的，这里之所以要把目录放入跟ID对照的map中，是为了以后扩展方便
				}
			}
			
		}  
		String dir="/";  
		if(site!=null){ 
			String type=req.getParameter("type"); 
			if(!StringUtils.isNullOrEmpty(type) && type.trim().toLowerCase().equals(WebSite.WEBPAGE_TYPE_VIEWER.toString())){
				dir=req.getContextPath()+"/sites/"+site.getDirectory()+"/";
			} 
		}
		for(Long key:dirMap.keySet()){
			dir+=dirMap.get(key)+"/"; 
		}
		dir=dir+"index.html";
		return dir;
	}

	protected void _init() {
		if(!StringUtils.isNullOrEmpty(nodeId)){
			if(nodeId.toUpperCase().trim().equals("OWNER")){
				nodeId=getRequest().getParameter("nodeId");
			}else if(StringUtils.isNumber(nodeId)){
				 
			}else{
				nodeId="-1";
			}
			Long currentNodeId=Long.valueOf(nodeId);
			if(!currentNodeId.equals(-1L)){
				INodeService nodeServ=(INodeService) ServiceProxyFactory.getServiceProxy(NodeServiceImpl.class);
				List<NodeEntity> nl=nodeServ.getList("from "+nodeServ.getTableName()+" where nodeIdPath like '%,"+currentNodeId+",'",null);
				if(nl==null)
					return;
				if(nl.size()==0)
					return;
				for(NodeEntity n:nl){
					NodeExtEntity ext=new NodeExtEntity();
					ext.setNode(n);
					INodeAttrService attrServ=(INodeAttrService) ServiceProxyFactory.getServiceProxy(NodeAttrServiceImpl.class);
					NodeAttrEntity attr=attrServ.getNodeAttr(currentNodeId);
					ext.setAttr(attr);
					nodeList.add(ext);
				}
			}
		}
	}

	public void setNodeId(String nodeId) {
		this.nodeId = nodeId;
	}

	public String getNodeId() {
		return nodeId;
	}
}